package com.lagou.client;

import com.alibaba.fastjson.serializer.JSONSerializer;
import com.lagou.util.*;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.ZkClient;
import org.apache.zookeeper.data.Stat;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class RpcConsumer {
    //创建线程池对象
    private static ExecutorService executor =
            Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    private static UserClientHandler userClientHandler;
    //private boolean flag =true;

    private static Map<String,UserClientHandler> clientMap =new HashMap<String, UserClientHandler>();
    //private static List<String> portList =new ArrayList<String>();

    static AtomicInteger ai = new AtomicInteger(0);

    //1.创建一个代理对象  providerName: UserService#sayHello
    public Object createProxy(final Class<?> serviceClass){
        //借助JDK动态代理生成代理对象
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[]{serviceClass}, new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //(1) 调用初始化netty客户端的方法
//                if (userClientHandler ==null){
//                    initClient();
//                }

                //组装RpcRequest对象
                RpcRequest rpcRequest = new RpcRequest();
                rpcRequest.setRequestId("1");
                rpcRequest.setClassName("com.lagou.service.UserServiceImpl");//UserService
                rpcRequest.setMethodName("sayHello");
                Object[] paraObjArr ={args[0]};
                rpcRequest.setParameters(paraObjArr);
                Class[] paraTypeArr ={String.class};
                rpcRequest.setParameterTypes(paraTypeArr);

                //设置参数
                //userClientHandler.setPara(providerName+args[0]);

                //String serverPort =getServerPort();
                String serverPort =selectServerPort();
                UserClientHandler userClientHandler = clientMap.get(serverPort);

                userClientHandler.setPara(rpcRequest);

                //请求记录
                ZkClient zkClient = new ZkClient("114.215.81.54:2181");
                zkClient.writeData("/serverlist/127.0.0.1:"+serverPort,"");
                //long l = System.currentTimeMillis();

                //去服务端请求数据
                return executor.submit(userClientHandler).get();
            }
        });
    }

    public static String getServerPort(){
        // 获取集群服务器数量
        int serverCount = clientMap.size();
        // 负载均衡轮询算法，算出要调用的机器. 请求数%服务器数量=机器位置
        // getAndIncrement 表示count++操作
        List<String> portList = new ArrayList<String>(clientMap.keySet());
        String serverPort = portList.get(ai.getAndIncrement() % serverCount);
        return serverPort;
    }

    //分配服务器
    public static String selectServerPort(){
        ZkClient zkClient = new ZkClient("114.215.81.54:2181");
        //服务器数量
        if(clientMap.size() >1){//目前两台做比较
            //节点信息
            Stat stat1 =new Stat();
            Object data1 = zkClient.readData("/serverlist/127.0.0.1:8990", stat1);
            Stat stat2 =new Stat();
            Object data2 = zkClient.readData("/serverlist/127.0.0.1:8991", stat2);
            if(data1 ==null || data2 ==null){
                return getServerPort();
            }else{
                Long requestTime1 = Long.valueOf(String.valueOf(data1));
                Long responseTime1 = Long.valueOf(String.valueOf(stat1.getMtime()));
                long time1 =responseTime1-requestTime1;
                System.out.println(stat1.getMtime());

                Long requestTime2 = Long.valueOf(String.valueOf(data2));
                Long responseTime2 = Long.valueOf(String.valueOf(stat2.getMtime()));
                long time2 =responseTime2-requestTime2;
                System.out.println(stat2.getMtime());

                if(time1==time2){//响应时间相同
                    return getServerPort();
                }else if(time1 <time2){
                    return "8990";
                }else {
                    return "8991";
                }
            }

        }else{
            return getServerPort();
        }
    }

    //2.初始化netty客户端
//    public static void initClient() throws InterruptedException {
//        userClientHandler = new UserClientHandler();
//
//        EventLoopGroup group = new NioEventLoopGroup();
//        Bootstrap bootstrap = new Bootstrap();
//        bootstrap.group(group)
//                .channel(NioSocketChannel.class)
//                .option(ChannelOption.TCP_NODELAY,true)
//                .handler(new ChannelInitializer<SocketChannel>() {
//                    protected void initChannel(SocketChannel ch) throws Exception {
//                        ChannelPipeline pipeline = ch.pipeline();
//                        //pipeline.addLast(new StringEncoder());
//                        //pipeline.addLast(new StringDecoder());
//                        pipeline.addLast( new RpcEncoder(RpcRequest.class, new JSONSerializerZDY()));
//                        pipeline.addLast( new RpcDecoder(RpcResponse.class, new JSONSerializerZDY()));
//                        pipeline.addLast(userClientHandler);
//                    }
//                });
//
//        //bootstrap.connect("127.0.0.1",8990).sync();
//        //bootstrap.resolver()
//        //获取zookeeper的服务器列表信息
//        ZkClient zkClient = new ZkClient("114.215.81.54:2181");
//        System.out.println("会话被创建了。。");
//        List<String> children = zkClient.getChildren("/serverlist");
//        System.out.println(children);
//        for (int i=0;children !=null && i<children.size();i++){
//            String[] serverStrings = children.get(i).split(":");
//            String ipStr =serverStrings[0];
//            int host =Integer.parseInt(serverStrings[1]);
//            System.out.println("server号："+ipStr+":"+host);
//            bootstrap.connect(ipStr,host).sync();
//        }
//        zkClient.subscribeChildChanges("/serverlist", new IZkChildListener() {
//            public void handleChildChange(String parentPath, List<String> list) throws Exception {
//                System.out.println(parentPath +"is child changed,currentChilds:"+list);
//
//
//            }
//        });
//    }

    public void initClient02() throws InterruptedException {
        ZkClient zkClient = new ZkClient("114.215.81.54:2181");
        System.out.println("会话被创建了。。");
        final List<String> children = zkClient.getChildren("/serverlist");
        System.out.println(children);
        for (int i=0;children !=null && i<children.size();i++){
            String[] serverStrings = children.get(i).split(":");
            String host =serverStrings[0];
            int port =Integer.parseInt(serverStrings[1]);
            System.out.println("server号："+host+":"+port);

            initClientConnection(host,port);
        }

        zkClient.subscribeChildChanges("/serverlist", new IZkChildListener() {
            public void handleChildChange(String parentPath, List<String> list) throws Exception {
                System.out.println(parentPath +"is child changed,currentChilds:"+list);

                Map<String,UserClientHandler> newClientMap =new HashMap<String, UserClientHandler>();
                for(int i=0;i<list.size();i++){
                    String[] serverStrings = list.get(i).split(":");
                    UserClientHandler clientHandler = clientMap.get(serverStrings[1]);
                    if (clientHandler !=null){
                        newClientMap.put(serverStrings[1],clientHandler);
                    }else {//新增服务器的情况
                        String host =serverStrings[0];
                        int port =Integer.parseInt(serverStrings[1]);
                        initClientConnection(host,port);
                        newClientMap.put(serverStrings[1],clientMap.get(serverStrings[1]));
                    }
                }
                //用新的服务器列表替换旧的
                clientMap =newClientMap;
            }
        });
    }

    public static void initClientConnection(String host,int port) throws InterruptedException {
        userClientHandler = new UserClientHandler();

        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY,true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        //pipeline.addLast(new StringEncoder());
                        //pipeline.addLast(new StringDecoder());
                        pipeline.addLast( new RpcEncoder(RpcRequest.class, new JSONSerializerZDY()));
                        pipeline.addLast( new RpcDecoder(RpcResponse.class, new JSONSerializerZDY()));
                        pipeline.addLast(userClientHandler);
                    }
                });
        bootstrap.connect(host,port).sync();
        clientMap.put(port+"",userClientHandler);
    }
}
